import router from '../router/index'
import axios from 'axios'
let token = localStorage.getItem('token');

const service = axios.create({
    timeout: 15000,
    headers: {
        userId: 1,
        projectId: 1,
        'token': '907a1f3a-2967-4381-8cb2-408610a3f19b',
        'Content-Type': 'application/json'
    }
})

service.interceptors.request.use(
    config => {
        // let apiUrl = config.url
        // let allUrl = [
        //     '/warn/warnDispatch',
        //     '/warn/statistics',
        //     '/warn/deviceList',
        //     '/device/drop/monitorType',
        //     '/rain/getRainfallData',
        //     '/device/polymerize',
        //     '/warn/getUnProcessWarnRecord',
        //     '/warn/getRealTimeWarn',
        //     '/monitor/type/count',
        //     '/monitor/area/count',
        //     '/patrol/statistics',
        //     '/device/rank',
        //     '/device/online/rate'
        // ];
        // let needAuthorization = allUrl.includes(apiUrl);
        // let accesstoken = localStorage.getItem('token');
        // config.headers.Authorization = accesstoken;
        // // console.log('该接口是否需要登录：true为不需要',needAuthorization,'请求接口：',apiUrl)
        // if(needAuthorization) {
        //     return config
        // } else {
        //     if(!accesstoken) {
        //         router.push('/login')
        //         return
        //     }else {
        //         return config
        //     }
        // }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response => {
        if (response.data.code === 403) {
            router.push('/403')
        } else if (response.status === 200) {
            if (response.data.code == 200) {
                if (!response.data.data) {
                    response.data.data = '';
                }
                return Promise.resolve(response.data)
            } else if (response.data.code == 403) {
                router.push('/403')
            } else if (response.data.code == 401) {
                router.push('/login')
            } else {
                return Promise.reject(response.data)
            }
        } else {
            Promise.reject(response.data);
        }
    },
    error => {
        if (error.response.data.code == 401) {
            router.push('/login');
        } else if (error.response.data.code == 403) {
            router.push('/403')
        }
        return Promise.reject(error.response)
    }
)
export default service